package com.mjk.common.web.getway.utils.loadbalancer.impl;

import com.mjk.common.web.getway.utils.loadbalancer.AbstractLoadBalancer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态负载均衡示例算法：最小连接数
 */
public class LeastConnectionsLoadBalance extends AbstractLoadBalancer {
    private Map<String, Integer> serverConnections;

    public LeastConnectionsLoadBalance(List<String> servers) {
        serverConnections = new HashMap<>();
        for (String server : servers) {
            serverConnections.put(server, 0);
        }
    }
    @Override
    public String getNextServer(String key) {
        int minConnections = Integer.MAX_VALUE;
        String selectedServer = "";

        for (Map.Entry<String, Integer> entry : serverConnections.entrySet()) {
            if (entry.getValue() < minConnections) {
                minConnections = entry.getValue();
                selectedServer = entry.getKey();
            }
        }
        serverConnections.put(selectedServer, serverConnections.get(selectedServer) + 1);
        return selectedServer;

    }
}
